<template>
  <Dialogdrawerdefect size="900px" :ddtvisible.sync="visible" @close="handleCancel" :title="title" direction="rtl" :has-modal="false" :modal="false" :close-on-click-modal="true">
    <div class="mianBox cont_box" style="padding-top: 0px !important;" v-loading="loading">
      <el-form inline class="rule-form" ref="form" :model="ruleForm" :rules="rules">
        <el-row>
          <el-col :span="12" v-show="false">
            <el-form-item label="医院名称:" label-width="110px" prop="hospitalName">
              <el-select size="small" class="param-type_input" v-model="ruleForm.hospitalCode" placeholder="请选择" @change="handleChange('hospital')">
                <el-option
                  v-for="(item,index) in mx_hospitalList"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="医院编码:" label-width="110px" prop="hospitalCode">
              <el-input size="small" v-model="ruleForm.hospitalCode" placeholder="请输入" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="areaName">
              <template slot="label">
                <span>院区:</span>
              </template>
              <el-select v-model="ruleForm.areaName" @change="handleChange('areaName')" size="small" class="param-type_input" clearable v-select-create filterable default-first-option placeholder="请选择" collapse-tags>
                <el-option v-for="(item,index) in areaNameOptions" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="parameterType">
              <template slot="label">
                <span>参数类型:</span>
              </template>
              <el-select
                :disabled="curStatus=='edit'"
                size="small"
                class="param-type_input"
                @change="parameterTypeChange()"
                v-select-create
                filterable
                default-first-option
                v-model="ruleForm.parameterType"
                placeholder="请选择"
                clearable
                collapse-tags>
                <el-option
                  v-for="(item,index) in ParameterTypeOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" prop="ipRange">
              <template slot="label">
                <span>IP地址:</span>
              </template>
              <el-input size="small" ref="age" v-model="ruleForm.ipRange" placeholder="IP地址" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" label-width="110px" prop="remark">
              <el-input
                class="long-input"
                type="textarea"
                size="small"
                v-model="ruleForm.remark"
                placeholder="请输入"
                :autosize="{ minRows: 3, maxRows: 4}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <userPermissionConfiguration ref="upconfig" :isshowbtn="false" v-if="!showClinicConfig"></userPermissionConfiguration>
        <clinicalSelfConfigForm ref="clinicalConfig" :isshowbtn="false" v-else></clinicalSelfConfigForm>
        <div class="buttons flex flex-row justify-between align-center">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link cursor">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="reset">重置表单</el-dropdown-item>
              <el-dropdown-item command="delete" v-if="curStatus === pageStatus.edit">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-checkbox
            style="margin-left: 10px;"
            v-if="curStatus === pageStatus.add"
            v-model="defaultChecked"
            @change="setDefaultFormData">赋值默认</el-checkbox> -->
          <div class="right-buttons">
            <el-button class="floatR m-l-1" type="primary" size="small" @click="handleConfirm(true)" v-if="curStatus === 'edit'">已此为模板新建</el-button>
            <el-button class="floatR m-l-1" type="primary" size="small" @click="handleConfirm(false)">确定</el-button>
            <el-button class="floatR" size="small" @click="handleClose">取消</el-button>
          </div>
        </div>
      </el-form>
    </div>
  </Dialogdrawerdefect>
</template>
<script>
import userPermissionConfiguration from '@/components/appConfig/check/userPermissionConfiguration'
import clinicalSelfConfigForm from '@/components/appConfig/check/clinicalSelfConfigForm'
import Dialogdrawerdefect from '@/components/dialogbox/dialogDrawerDefect'
// import { Options } from '@/utils/constant'
import { mapGetters } from 'vuex'
import { PageStatus } from '@/utils/constant'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { setIsShowTwoList, setIsSetStorageAreaName } from '@/utils/utils'
import {
  getClientParamModelByIP,
  getClientParamgModel,
  addClientParam,
  deleteMessage,
  editClientParam
} from '@/api/api.js'
export default {
  props: {
    // 是否弹出右侧
    showRight: {
      Boolean,
      default: false
    },
    // 判断是新增还是编辑
    curStatus: {
      String,
      default: ''
    },
    // 标题
    title: {
      String,
      default: ''
    },
    rowData: {
      Object,
      default: () => {}
    },
    hospitalCode: {
      String,
      default: ''
    },
    areaname: {
      String,
      default: ''
    }
  },
  components: {
    Dialogdrawerdefect,
    clinicalSelfConfigForm,
    userPermissionConfiguration
  },
  computed: {
    ...mapGetters(['areaNameOptions', 'clientIP'])
  },
  beforeDestroy() {
    console.log('beforeDestroy edit')
    this.timeout01 && clearTimeout(this.timeout01)
    this.timeout02 && clearTimeout(this.timeout02)
    this.timeout03 && clearTimeout(this.timeout03)
  },
  data() {
    return {
      loading: false,
      ParameterTypeOptions: ['医技Web', '临床Web'],
      pageStatus: PageStatus,
      showClinicConfig: false, // 显示临床的还是医技的
      visible: false,
      ruleForm: {
        hospitalCode: this.hospitalCode,
        areaName: this.areaname,
        parameterType: '医技Web',
        ipRange: '',
        parameterContent: '',
        remark: ''
      },
      rules: {
        // areaName: { message: '请选择院区', trigger: 'blur' },
        parameterType: { required: true, message: '请输入参数类型', trigger: 'blur' },
        ipRange: { required: true, message: '请输IP地址', trigger: 'blur' },
        age: {
          required: false,
          message: '开始年龄要小于结束年龄',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (parseInt(this.ruleForm.ageEnd) >= parseInt(value) || (isNaN(parseInt(this.ruleForm.age)) && isNaN(parseInt(this.ruleForm.ageEnd)))) {
              // console.error('来这里了嘛')
              callback()
            } else {
              callback(new Error('开始年龄要小于结束年龄'))
            }
          }
        }
      }
    }
  },
  async mounted() {
    this.visible = this.showRight
    // await this.$store.dispatch('settings/set_appointTypeOptions', { HospitalCode: this.ruleForm.hospitalCode || this.hospitalCode, type: '预约来源' })
    // await this.$store.dispatch('settings/set_hisTypeOptions', { HospitalCode: this.ruleForm.hospitalCode || this.hospitalCode, type: 'HIS类型' })
    // this.ruleForm.hospitalCode = this.$store.state.user.hospitalCode
    // this.getAllListData()
  },
  watch: {
    async visible(val) {
      this.$emit('update:showRight', val)
      if (val) {
        // this.ruleForm.hospitalCode = this.hospitalCode
        // this.$nextTick(() => {
        //   if (this.rowData) {
        //     // this.ruleForm = this.rowData
        //     console.log('visible=>this.rowData', this.rowData)
        //     this.getClientParamgModel(this.rowData.id)
        //   } else {
        //     console.log('visible=>setDefaultFormData')
        //     this.setDefaultFormData()
        //   }
        // })
      }
    },
    showRight(val) {
      this.visible = val
    },
    formData(data) {
      if (data && this.visible) {
        this.setDefaultFormData()
      }
    }
    // hospitalCode: {
    //   handler(val) {
    //     if (val && this.visible) {
    //       this.ruleForm.hospitalCode = val
    //       this.handleChange('hospital')
    //     }
    //   },
    //   immediate: true
    // }
  },
  methods: {
    resetDialog() {
      this.ruleForm.hospitalCode = this.hospitalCode
      this.$nextTick(() => {
        if (this.rowData) {
          // this.ruleForm = this.rowData
          console.log('visible=>this.rowData', this.rowData)
          this.getClientParamgModel(this.rowData.id)
        } else {
          console.log('visible=>setDefaultFormData')
          this.setDefaultFormData()
        }
      })
    },
    getClientParamModelByIPEvent() {
      let params = {
        HospitalCode: this.hospitalCode,
        ParameterType: '医技Web',
        IpAddress: this.clientIP
      }
      console.log('getClientParamModelByIP=>params', params)
      getClientParamModelByIP(params).then(res => {
        console.log('getClientParamModelByIP=>res', res)
        if (res.code === 10000) {
          // console.log()
          if (res.content) {
            // 如果客户端的ip被配置参数给指定了（被安排了），就用接口里的参数配置
            if (res.content.ipRange == this.clientIP) {
              // 把res.content.parameterContent里的配置参数覆盖到本地缓存的localSetMemory里、defaultReadCard里、UserPermision里
              const parameterContent = JSON.parse(res.content.parameterContent)
              console.log('parameterContent', parameterContent)
              setLocalStorage('localSetMemory', res.content.parameterContent)
              setLocalStorage('UserPermision', parameterContent.registerRoom)
              setIsShowTwoList(parameterContent.isShowTwoList || false)
              setIsSetStorageAreaName(parameterContent.isSetStorageAreaName || false)
              if (this.isMoreReadCardCheck) {
                setLocalStorage('defaultReadCard', parameterContent.defaultReadCard)
              }
            } else {
              // 否则就在IP范围内，判断客户端本地是否有缓存，若没缓存，才取IP范围内的配置
              const localSetMemory = getLocalStorage('localSetMemory')
              if (localSetMemory) {
                // 若有缓存则取缓存的，不用动，会自动取的
              } else {
                // 若客户端本身没缓存，则取接口里的IP范围的值
                const parameterContent = JSON.parse(res.content.parameterContent)
                console.log('parameterContent', parameterContent)
                setLocalStorage('localSetMemory', res.content.parameterContent)
                setLocalStorage('UserPermision', parameterContent.registerRoom)
                setIsShowTwoList(parameterContent.isShowTwoList || false)
                setIsSetStorageAreaName(parameterContent.isSetStorageAreaName || false)
                if (this.isMoreReadCardCheck) {
                  setLocalStorage('defaultReadCard', parameterContent.defaultReadCard)
                }
              }
            }
          }
        }
      })
    },
    getClientParamgModel(id) {
      let params = {
        HospitalCode: this.hospitalCode,
        id
      }
      getClientParamgModel(params).then(res => {
        // console.log('getClientParamgModel=>res', res)
        if (res.code == 10000) {
          this.loading = false
          this.ruleForm = res.content
          this.parameterTypeChange()
          this.$nextTick(() => {
            if (this.ruleForm.parameterType == '医技Web') {
              this.$refs.upconfig.setFormData(JSON.parse(this.ruleForm.parameterContent))
            } else {
              this.$refs.clinicalConfig.setFormData(JSON.parse(this.ruleForm.parameterContent))
            }
          })
        }
      })
    },
    // 设置赋值默认值
    setDefaultFormData() {
      console.log('setDefaultFormData')
      this.ruleForm.areaName = this.areaname
      this.ruleForm.parameterType = '医技Web'
      this.showClinicConfig = false
      this.ruleForm.ipRange = ''
      this.ruleForm.parameterContent = ''
      this.ruleForm.remark = ''
      this.$nextTick(() => {
        this.curStatus && (!this.showClinicConfig ? this.$refs.upconfig.reset() : this.$refs.clinicConfig.reset())
      })
    },
    handleCommand(command) {
      switch (command) {
        case 'reset':
          this.handleReset()
          break
        case 'delete':
          this.delete()
          break
        default:
          break
      }
    },
    // 切换成临床web的时候，下面的表格换成临床预约的web配置
    parameterTypeChange() {
      if (this.ruleForm.parameterType == '临床Web') {
        this.showClinicConfig = true
      } else {
        this.showClinicConfig = false
      }
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.ruleForm.remark = ''
          break
        case 'dep':
          this.ruleForm.remark = ''
          break
        case 'modality':
          this.ruleForm.remark = ''
          break
        default:
          break
      }
    },
    delete() {
      /* 删除 */
      this.$confirm('此操作将永久删除该短信, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData()
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData() {
      deleteMessage({ id: this.ruleForm.id, hospitalCode: this.ruleForm.hospitalCode }).then((res) => {
        if (res.code === 10000) {
          this.$message.success('删除成功')
          this.handleClose()
          this.refresh()
        }
      })
    },
    handleClose() {
      this.$emit('update:showRight', false)
      this.handleCancel()
    },
    handleCancel() {
      // 关闭弹窗
      this.handleReset()
    },
    handleReset() {
      /* 重置 */
      this.setDefaultFormData()
    },
    // 获取下拉数据
    getAllListData() {
      // const that = this
      return new Promise(async (resolve, reject) => {
        const res = Promise.all([
          // that.getMessageType(),
          // that.getBigPartOptions(),
          // that.getMessageInfo(),
          // that.getItemGroupList()
        ])
        if (res) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    },
    handleConfirm(flag) {
      this.$refs.form.validate((valid, object) => {
        if (valid) {
          if (this.curStatus === 'add') {
            /* 新增保存 */
            this.save('add')
          } else {
            // 以此为模板新增
            if (flag) {
              /* 新增保存 */
              delete this.ruleForm.id
              this.save('add')
            } else {
              /* 编辑保存 */
              this.save()
            }
          }
        } else {
          this.timeout01 = setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          for (let k in object) {
            this.$message.warning(object[k][0].message)
            return
          }
        }
      })
    },
    save(addFlag) {
      /* 新增保存 */
      this.loading = true
      let data = {
        ...this.ruleForm
      }
      const setttingFormData = !this.showClinicConfig
        ? this.$refs.upconfig.getFormData()
        : this.$refs.clinicalConfig.formdata
      data.parameterContent = JSON.stringify(setttingFormData)
      let tempAjax = addFlag ? addClientParam : editClientParam
      tempAjax(data).then((res) => {
        this.loading = false
        if (res.code === 10000) {
          if (!addFlag && data.ipRange == this.clientIP) {
            this.getClientParamModelByIPEvent()
          }
          this.$message.success(addFlag ? '新增成功' : '编辑成功')
          // this.ruleForm.id = res.content.id
          this.$emit('refresh')
          this.timeout02 = setTimeout(() => {
            this.visible = false
          }, 300)
        }
      })
    },
    changeStatus(status) {
      this.ruleForm.isOpen = status
    },
    refresh() {
      // 本地缓存排班管理的机房选择数据重置默认选项
      // this.$store.dispatch('user/getDefaultCheckRoomTree')
      // this.$store.dispatch('user/resetDefaultCheckRoom', [])
      // console.error('来这里了嘛')
      // this.getAllListData()
      this.$emit('refresh')
    }
  }
}
</script>
<style lang='scss' scoped>
.add_department{
  font-size: 14px;
  cursor: pointer;
  color: #00c0ef;
  &:hover{
    opacity: 0.6;
  }
}
/deep/ .el-form-item__label{
  text-align: right;
}
.mianBox{
  /* /deep/ .el-input{
    width: 215px;
  } */
  .long-input{
    width: 555px;
    /deep/ .el-input{
        width: 500px;
    }
  }
  .name{
    font-weight: bold;
  }
  .el-form--inline .el-form-item{
    margin-right:0px;
    margin-bottom: 16px;
  }
  /deep/ .el-form-item__label{
    line-height: 32px;
  }
  /deep/ .el-form-item__content{
    line-height: 32px;
  }
  .buttons{
    width: 100%;
    .el-dropdown{
      color: #00c0ef;
    }
  }
  .pointer {
    cursor: pointer;
  }
}
/* 自定义上下文菜单样式 */
.context-menu {
  position: fixed; /* 或者 absolute */
  /* background-color: #fff; */
  /* border: 1px solid #ccc; */
  padding: 5px;
  z-index: 500;
}
.box-card >>> .el-card__body,.box-card >>> .el-card__header{
  text-align:center;
  padding: 0px;
}
.long-info {
  width: 100%;
  border: 0.3px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px 15px;
  padding: 10px;
  font-size: 14px;
  line-height: 1.5;
  font-size: inherit;
  max-height: 300px; /* 设置最大高度 */
  transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  overflow: auto; /* 超出最大高度时显示滚动条 */
}
.long-info:focus {
  border: 0.3px solid #dcdfe6;/* 将边框宽度设置为1px */
  /* box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2); */
  outline-color: #00C0EF;
  outline-width: 0.2px;
  outline-style: solid;
}
/* 输入框placeholder的样式 */
.long-info::placeholder {
  color: #c9c9c9; /* placeholder文本颜色 */
}
.long-info {
  resize:vertical; /* 只能水平调整元素大小 */
}
/deep/ .text-item:hover{
  background-color: #dcdfe6;
}
.text-item{
  color: black;
  border-bottom:1px solid #ebeef5;
  transition: 0.5s;
  cursor: pointer;
}
.cursor{
  cursor: pointer;
}
</style>

